
var rokuSettingsDivHTML = '<div id="rokuSettingsDiv" style="outline-width: 0px; outline-style: initial; outline-color: initial; position: absolute; display: block; z-index: 1002; height: auto; width: 593px; top: 0px; left: 476px; " class="ui-dialog ui-widget ui-widget-content ui-corner-all modalLightbox settingsDialog ui-resizable" tabindex="-1" role="dialog" aria-labelledby="ui-dialog-title-1"> \
	<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" unselectable="on" style="-webkit-user-select: none; "> \
		<span class="ui-dialog-title" id="ui-dialog-title-1" unselectable="on" style="-webkit-user-select: none; ">&nbsp;</span> \
	</div> \
<div class="ui-dialog-content ui-widget-content" style="width: auto; min-height: 125px; height: auto; " scrolltop="0" scrollleft="0"> \
<div class="settings_view"> \
  <div class="settings_nav"> \
    <div class="settings_shadow"> \
    <ul> \
      <li class="main morgku selected">Morgku</li> \
    </ul> \
    </div> \
  </div> \
  <div class="settings_content"><div class="change_email_pass subview"> \
  <h1 class="title">Roku IP Address and Mog App ID</h1> \
  	<p>On your Roku, go to "Roku Player Settings" and then "player info" to \
	find the Roku IP address.</p> \
  <form> \
    <ul class="info_list"> \
      <li id="roku_ip_list"> \
        <label for="roku_ip">Roku IP Address</label> \
        <input type="text" value="192.168.1.3" size="16" maxlength="16" name="roku_ip" id="roku_ip" tabindex="1"> \
      </li> \
      <li id="roku_mog_id"> \
        <label for="roku_mogId">Mog App Id</label> \
        <input type="text" value="" size="6" maxlength="6" name="roku_mogId" id="roku_mogId" tabindex="2"> \
      </li> \
    </ul> \
  </form> \
      <p>You probably don\'t need to change the app ID, but if you do, go to  \
    http://{your-roku-ip}:8060/query/apps (replacing {your-roku-ip} with the IP address from above) \
    and find the ID for "MOG music".<br><br></p>\
    <p>Morgku was written by <a href="mailto:olivers@mondrian-ide.com">Oliver Smith</a> and modified for the new Mog interface by <a href="mailto:gonzotek@gmail.com">A. Cassidy Napoli</a>.<br><br></p> \
  <div clas8s="buttons"> \
  	<div id="rokuCancelBtn" class="button shiny-button wide"> \
  		<div class="button-text">Cancel</div> \
  	</div> \
  <div id="rokuSaveBtn" class="button shiny-button dialog-default wide"> \
  	<div class="button-text">Save</div> \
  </div> \
  </div> \
  <p class="error" style="display:none;"></p> \
  </div> \
  </div> \
</div> \
</div> \
<div class="ui-resizable-handle ui-resizable-n" unselectable="on" style="-webkit-user-select: none; "></div> \
<div class="ui-resizable-handle ui-resizable-e" unselectable="on" style="-webkit-user-select: none; "></div> \
<div class="ui-resizable-handle ui-resizable-s" unselectable="on" style="-webkit-user-select: none; "></div> \
<div class="ui-resizable-handle ui-resizable-w" unselectable="on" style="-webkit-user-select: none; "></div> \
<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se" style="z-index: 1001; -webkit-user-select: none; " unselectable="on"></div> \
<div class="ui-resizable-handle ui-resizable-sw" style="z-index: 1002; -webkit-user-select: none; " unselectable="on"></div> \
<div class="ui-resizable-handle ui-resizable-ne" style="z-index: 1003; -webkit-user-select: none; " unselectable="on"></div> \
<div class="ui-resizable-handle ui-resizable-nw" style="z-index: 1004; -webkit-user-select: none; " unselectable="on"></div> \
</div>';

function loadOptions() {  
  chrome.extension.sendRequest({name: "getPrefs"},
     function(response)
     {
	    var ip = response.ip;
	    var id = response.appId;
	    if(ip==undefined)ip="192.168.1.3";
	    if(id==undefined)id="2136";
        document.getElementById('roku_ip').value = ip;
		document.getElementById('roku_mogId').value = id;
     });
}

function saveOptions() {
  var ip = document.getElementById('roku_ip').value;
  var id  = document.getElementById('roku_mogId').value;
  chrome.extension.sendRequest({name: "setPrefs", rokuIp: ip, appId: id});
  
}

function morgkuSettings(){
	var rokuSettingsDivContainer = document.getElementById("rokuSettingsDivContainer");
	if(!rokuSettingsDivContainer){
		rokuSettingsDivContainer = document.createElement('div');
		rokuSettingsDivContainer.setAttribute('id','rokuSettingsDivContainer');
	}
	rokuSettingsDivContainer.innerHTML = rokuSettingsDivHTML;
	document.body.appendChild(rokuSettingsDivContainer);
	var rokuSettingsDiv = document.getElementById("rokuSettingsDiv");
	loadOptions();
	var rokuSaveBtn = document.getElementById("rokuSaveBtn");
	var rokuCancelBtn = document.getElementById("rokuCancelBtn");
	rokuSaveBtn.onclick = function(){
		saveOptions();
		rokuSettingsDivContainer.removeChild(rokuSettingsDiv);
		}
	rokuCancelBtn.onclick = function(){
		rokuSettingsDivContainer.removeChild(rokuSettingsDiv);
		}
	return false;
}

String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
}

Object.prototype.firstObject = function() {
    var n = this;
    n = n.firstChild;
    if (n && n.nodeType != 1)
      n = n.nextObject();
    return n;
}

Object.prototype.nextObject = function() {
    var n = this;
    do n = n.nextSibling;
    while (n && n.nodeType != 1);
    return n;
}

function launch(trackIds) {
  chrome.extension.sendRequest({ name: 'launch', 'trackIds': trackIds });
};

function createRokuLink(trackIds) {
  var rokuLink = document.createElement('span');
  rokuLink.setAttribute('class', 'roku'); 
  rokuLink.setAttribute('trackId',trackIds);
  rokuLink.addEventListener('click', 
      new Function('launch([ "' + trackIds.join('", "') + '" ]);event.stopPropagation();'));
  rokuLink.appendChild(document.createTextNode('R'));
  return rokuLink;
};

function addTrackLinks() {
  var listItems = document.getElementsByTagName('li');
  for (var i = 0; i < listItems.length; i++) {
    trackId = listItems[i].getAttribute('track_id');
    if(trackId!="" && trackId!=null) {
	    var rokuLink = createRokuLink([ trackId ]);
	    if (listItems[i].getElementsByTagName('div')[0] && listItems[i].getElementsByTagName('div')[0].getAttribute('class')=="track_container clrfx") {
		    listItems[i].getElementsByTagName('div')[0].appendChild(rokuLink);
	    } else {
	    listItems[i].appendChild(rokuLink);
   		};
    };
  };
};

function addAlbumLink() {
	var album = document.getElementById('album');
	var trackIds = [];
	var listItems = album.getElementsByTagName('li');
	for (var i = 0; i < listItems.length; i++) {
    	trackId = listItems[i].getAttribute('track_id');
    	if(trackId!="" && trackId!=null) {
			trackIds.push(trackId);
		}
		albumClass = listItems[i].getAttribute('class');
   		if(albumClass=='play_album clrfx') var playAlbum = listItems[i];
    }
	var rokuLink = createRokuLink(trackIds);
	if(playAlbum) var addLink = playAlbum.getElementsByTagName("a")[0];
	if(addLink) rokuLink = playAlbum.insertBefore(rokuLink, addLink);
};

function addQueueLink() {
	var trackIds = [];
	var queueControls = document.getElementById("queue_controls");
	var realizedTracks = document.getElementById("realized");
	var listItems = realizedTracks.getElementsByTagName('li');
	for (var i = 0; i < listItems.length; i++) {
    	trackId = listItems[i].getAttribute('track_id');
    	if(trackId!="" && trackId!=null) {
			trackIds.push(trackId);
		}
    }
    var rokuLink = createRokuLink(trackIds);
    rokuLink.id = "rokuQueueLink";
    var rokuQueueLink = document.getElementById("rokuQueueLink");
    if(rokuQueueLink) queueControls.removeChild(rokuQueueLink);
    queueControls.appendChild(rokuLink);
};

function addPlaylistLink() {
  var trackIds = [];
  var playlist = document.getElementById('playlist_container');
  var listItems = playlist.getElementsByTagName('li');
  for (var i = 0; i < listItems.length; i++) {
    trackId = listItems[i].getAttribute('track_id');
    if(trackId!="" && trackId!=null) {
	    trackIds.push(trackId);
   		}
    }
    var rokuLink = createRokuLink(trackIds);
    var plTitle = playlist.firstObject();
    plTitle.appendChild(rokuLink);
};


//style rules
var styles = [];
styles.push("/*Plain Tracks*/             .roku {font-size:large; font-weight:900; visibility:hidden; display:none; color:#808080; text-shadow:0px 1px #000000;}  .roku:hover { color:#C7C7C7; text-shadow:0px 1px #000000;}");
styles.push("/*Playlist Tracks*/          #playlist_container .track:hover .roku{ display:inline; visibility: visible;  position: absolute; right: 686px; top: 6px; } #playlist_container .track .roku{ visibility: hidden;display:none; }");
styles.push("/*Top Tracks*/               #top_tracks li:hover .roku{ display:inline; visibility: visible; position: absolute; right: 50px; top: 2px; } #top_tracks li .roku{ visibility: hidden;display:none; }");
styles.push("/*Queued Tracks*/            #queue #realized .track:hover .roku{ display:inline; visibility: visible; position: absolute; left: 20px; top: 8px; } #queue #realized .track .roku{ visibility: hidden;display:none; }");
styles.push("/*Album Tracks*/             #album .track_container:hover .roku{ display:inline; visibility: visible;  position: absolute; left: 270px; top: 5px; } #album .track_container .roku{ visibility: hidden;display:none; }");
styles.push("/*Playlist Play All*/        #playlist .play_playlist:hover .roku{ display:inline; visibility: visible; position: absolute; right: 686px; top: 8px; } #playlist .play_playlist .roku{ position: absolute; right: 690px; top: 8px; display:none; visibility: hidden;}");
styles.push("/*Album Play All*/           #album .play_album:hover .roku{ display:inline; visibility: visible; position:relative; float:right; right: 35px; top: 5px; } .play_playlist .roku{ display:inline; visibility: hidden;}");
styles.push("/*Queue Controls*/           #queue_controls .roku{display:inline; position:relative; visibility:visible; top:7px;cursor:pointer}");
styles.push("/*Browse - Top Tracks*/        #browse .charts .track:hover .roku { display:inline; visibility: visible; position: absolute; right: 23px; top: 28px; } #browse .charts .track .roku  { display:inline; visibility: hidden;}");
styles.push("/*Artist - Top Tracks*/      .artistPane .track:hover .roku { display:inline; visibility: visible; position: absolute; right: 1px; top: 28px; } .artistPane .track .roku { display:inline; visibility: hidden;}");
styles.push("/*Top Artists - Top Tracks*/ .artistPane .track:hover .roku { display:inline; visibility: visible; position: absolute; right: 1px; top: 28px; } .artistPane .track .roku { display:inline; visibility: hidden;}");

var roku_sheet = document.createElement('style')
	roku_sheet.id = 'roku';
	roku_sheet.innerHTML = styles.join(" ");
document.body.appendChild(roku_sheet);

//Listen for changes to the url fragment
window.addEventListener('hashchange', new Function ('window.setTimeout(function() { addTrackLinks() }, 1000); ' + 
		'if (window.location.hash.startsWith("#playlist"))window.setTimeout(function() { addPlaylistLink() }, 1000); ' + 
		'if (window.location.hash.startsWith("#album"))window.setTimeout(function() { addAlbumLink() }, 1000); ' + 
		'if (window.location.hash.startsWith("#play_queue"))window.setTimeout(function() { addQueueLink() }, 1000); '
    ));

//On page load, Mog does a lot of initialization, so we have to wait until it's finished (3 second delay seems to work ok).
window.setTimeout(function() { addTrackLinks() }, 3000);
if (window.location.hash.startsWith("#playlist"))window.setTimeout(function() { addPlaylistLink() }, 3000);
if (window.location.hash.startsWith("#album"))window.setTimeout(function() { addAlbumLink() }, 3000);
if (window.location.hash.startsWith("#play_queue"))window.setTimeout(function() { addQueueLink() }, 3000);

window.setTimeout(function() {
	var dropMenusContainer = document.getElementById("menu-holder");
	var dropMenus = dropMenusContainer.getElementsByTagName("div");
	for(i=0;i<dropMenus.length;i++){
		if(dropMenus[i].getAttribute("class")=="menu-holder settings"){
			var menuPopDown = dropMenus[i].getElementsByTagName("ul");
			var rokuSettingsLink = document.createElement('li');
			rokuSettingsLink.innerHTML = "<a href='#' class='control' target='_blank'>Morgku Settings</a>";
			rokuSettingsLink.onclick = morgkuSettings;
			menuPopDown[0].appendChild(rokuSettingsLink);
			};
	}
},3000);

chrome.extension.sendRequest({name: "getPrefs"},
     function(response)
     {
		if(response.appId==undefined) morgkuSettings();
     });
